package yf.mall.component.app;

import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author yxmds
 */
@Slf4j
@Component
public class QiniuFileComponent {

    @Value("${Qiniu.img_domain}")
    private String imgDomain;

    @Value("${Qiniu.video_domain}")
    private String videoDomain;

    @Value("${Qiniu.AK}")
    private String AK;
    @Value("${Qiniu.SK}")
    private String SK;
    @Value("${Qiniu.bucket}")
    private String bucket;

    private static final List<String> IMG_SUFFIX = Arrays.asList("bmp", "gif", "jpg", "jpeg", "pjpeg", "x-png", "png");

    private static final List<String> PDF_SUFFIX = Arrays.asList("pdf");

    private static final List<String> VIDEO_SUFFIX = Arrays.asList("mp4","mov","avi","wmv","flv","mkv");

    private static final List<String> MUSIC_SUFFIX = Arrays.asList("mp3");

    private static final String HTTP_CODE = "http";

    private static final long EXPIRES = 3600;

    private static final String PRIVATE_FILE_TAG = "/private";

    public String complementFileUrl(String url) {
        if (StringUtils.isBlank(url)) {
            return url;
        }
        if (url.contains(HTTP_CODE)) {
            return url;
        }
        String fileType = url.substring(url.lastIndexOf('.') + 1, url.length()).toLowerCase();
        if (IMG_SUFFIX.contains(fileType)) {
            return imgDomain + url;
        } else if (VIDEO_SUFFIX.contains(fileType)) {
            return privateFileUrl(videoDomain + url);
        }
        return url;
    }

    public String privateFileUrl(String url) {
        if (StringUtils.isBlank(url) ) {
            return url;
        }
        Auth auth = Auth.create(this.AK, this.SK);
        return auth.privateDownloadUrl(url, EXPIRES);
    }
}

